package csu.web.mypetstore.web.servlet;

import com.alibaba.fastjson.JSONObject;
import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.UUID;
@WebServlet("/updateCartInfo")
public class UpdateCartServlet extends HttpServlet {
    private static final String CART_FORM = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String SUBMISSION_FLAG = "submissionFlag";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String AjaxItemId = req.getParameter("itemId");
        String AjaxQuantity = req.getParameter("quantity");

        System.out.println(AjaxItemId+" "+AjaxQuantity);

        HttpSession session = req.getSession();

        // 检查是否已经提交过表单
        if (session.getAttribute(SUBMISSION_FLAG) != null) {
            // 已经提交过表单，忽略这次提交
            req.getRequestDispatcher(CART_FORM).forward(req, resp);
            return;
        }

        Cart cart = (Cart) session.getAttribute("cart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();

        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                String quantityString = req.getParameter(itemId);
                int quantity = Integer.parseInt(quantityString);

                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {

            }
        }

        Account loginAccount = (Account) session.getAttribute("loginAccount");
        CartService cartService = new CartService();
        CatalogService catalogService = new CatalogService();
        if(loginAccount!=null)
        {
            if(cartService.checkCartByUserId(loginAccount.getUsername())){
                cartService.updateCArtInfo(loginAccount.getUsername(),cart);
            }else{
                cartService.insertCart(loginAccount.getUsername(),cart);
            }
            if(AjaxItemId!=null&&AjaxQuantity!=null){
            cartService.updateCartInfo(loginAccount.getUsername(),AjaxItemId,AjaxQuantity);
            Cart newcart = cartService.getCart(loginAccount.getUsername());
                if(cart!=null){
                    session.setAttribute("cart",newcart);

                    BigDecimal itemPrice = catalogService.getItem(AjaxItemId).getListPrice();
                    BigDecimal itemTotal = itemPrice.multiply(new BigDecimal(AjaxQuantity));
                    itemTotal.setScale(2, RoundingMode.HALF_UP);
                    // 创建 DecimalFormat 对象，并指定格式模式
                    DecimalFormat df = new DecimalFormat("$#,##0.00");
                    String itemTotal_str = df.format(itemTotal);

                    //计算修改后的总价钱
                    BigDecimal subTotal = new BigDecimal(00.00);
                    subTotal.setScale(2, RoundingMode.HALF_UP);
                    Iterator<CartItem> cartItems2 = newcart.getAllCartItems();
                    while (cartItems2.hasNext()) {
                        CartItem cartItem = (CartItem) cartItems2.next();
                        String itemId = cartItem.getItem().getItemId();
                        BigDecimal Price = cartItem.getItem().getListPrice();
                        Price = Price.multiply(new BigDecimal(cartItem.getQuantity()));
                        subTotal = subTotal.add(Price);
                    }
                    String subTotal_str = df.format(subTotal);

                    JSONObject json = new JSONObject();
                    json.put("itemTotal", itemTotal_str);
                    json.put("subTotal", subTotal_str);
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding("UTF-8");
                    resp.getWriter().write(json.toString());
                    resp.getWriter().close();
                }
            }
        }




        req.getRequestDispatcher(CART_FORM).forward(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // GET请求时删除提交标志
        HttpSession session = req.getSession();
        session.removeAttribute(SUBMISSION_FLAG);

        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}
